package com.bgds.sys.module.serviceimpl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bgds.sys.common.constant.BizConstant;
import com.bgds.sys.common.utils.TreeUtils;
import com.bgds.sys.module.entity.Device;
import com.bgds.sys.module.entity.Region;
import com.bgds.sys.module.entity.dto.DeviceDto;
import com.bgds.sys.module.mapper.DeviceMapper;
import com.bgds.sys.module.mapper.PermissionDeviceMapper;
import com.bgds.sys.module.service.IDeviceService;
import com.bgds.sys.module.service.IRegionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lj
 * @since 2020-01-06
 */
@Service
@Slf4j
public class IDeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {

    @Autowired
    protected PermissionDeviceMapper permissionDeviceMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Resource
    IRegionService iRegionService;


    /**
     * 菜单id获取设备
     *
     * @param permId 菜单ID
     * @return
     */
    @Override
    public List<DeviceDto> listByParam(Long permId) {
        List<DeviceDto> devices = permissionDeviceMapper.listByPermissionId(permId);
        //伺服阀监测页面，将区域装换父级设备，便于前端展示
        List<DeviceDto> regionDevices = new ArrayList<>();
        if (permId == 11) {
            Set<Region> regions = new LinkedHashSet();
            for (DeviceDto deviceDto : devices) {
                regions.add(deviceDto.getRegion());
            }
            for (Region region : regions) {
                DeviceDto deviceDto = new DeviceDto();
                deviceDto.setName(region.getName());
                deviceDto.setDeviceCode(region.getRegionCode());
                deviceDto.setParentCode(BizConstant.TOP_CODE);
                //设备父级编码设置为区域编码
                for (DeviceDto d : devices) {
                    if (d.getRegion().getRegionCode().equals(region.getRegionCode())) {
                        d.setParentCode(region.getRegionCode());
                    }
                }
                regionDevices.add(deviceDto);
            }
            devices.addAll(regionDevices);
            devices = devices.stream().filter(d -> !d.getName().contains("侧导板")).filter(d -> !d.getName().contains("卷取")).collect(Collectors.toList());
        }


        //构建设备树
        List<DeviceDto> list = null;
        if (permId != 18) {
            list = TreeUtils.listToTree(devices);
        } else {
            if (permId == 18) {
                devices = devices.stream().filter(d -> !d.getName().contains("侧导板")).collect(Collectors.toList());
            }
            JSONArray jsonArray = TreeUtils.listToJsonArray(devices);
            JSONArray objects = TreeUtils.treeList(jsonArray, BizConstant.TOP_CODE);
            list = JSONObject.parseArray(objects.toJSONString(), DeviceDto.class);
        }
        //对设备树子节点进行排序 规则：1.排序字段 降序 2.后根据名称
        list.forEach(device -> {
            List<DeviceDto> children = device.getChildren();
            if (!CollectionUtils.isEmpty(children)) {
                children.sort(Comparator.comparing(DeviceDto::getSortOrder).reversed().thenComparing(DeviceDto::getName));
            }
        });


        return list;
    }


    @Override
    public List<Device> listByParentCode(String parentCode) {
        return deviceMapper.seleteByParentCode(parentCode);
    }

    @Override
    public Device getOneByCode(String code) {
        Device device = deviceMapper.selectOne(new QueryWrapper<Device>().eq("device_code", code));
        return device;
    }

    @Override
    public List<Device> listPageDevice() {
        QueryWrapper<Device> wrapper = new QueryWrapper<>();
        wrapper.eq("device_flag", 0);
        List<Device> devices = deviceMapper.selectList(wrapper);
        return devices;
    }

    @Override
    public Region getRegionByRelationId(String relationId) {
        LambdaQueryWrapper<Device> qw = Wrappers.lambdaQuery();
        qw.eq(Device::getRelationId, relationId).select(Device::getRegionCode);
        List<Device> list = this.list(qw);
        if (CollectionUtils.isEmpty(list)){
            log.info("【德通报警列表】{},不存在该设备关联编码",relationId);
            return null;
        }
        Device device = list.get(0);
        QueryWrapper<Region> regionQw = new QueryWrapper<>();
        regionQw.lambda().eq(Region::getRegionCode,device.getRegionCode());
        return iRegionService.getOne(regionQw);
    }

    @Override
    public List<Device> listDeviceByCode(Set<String> codes) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("device_code", codes);
        return baseMapper.selectList(wrapper);
    }


}
